package xyz.xtgl.config.helper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import common.core.util.CommonUtil;
import common.core.util.CustomizeRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * @author liubo
 * @created 2020-02-03 21:51
 */
@Slf4j
public class QueryWrapperConverter implements Converter<String, QueryWrapper<?>> {

    public static final String query_wrapper = "queryWrapper";
    public static final String query_name="name";
    public static final String query_value="value";
    public static final String query_operator ="operator";
    public static final String operator_like="like";
    public static final String operator_in ="in";
    public static final String operator_eq ="eq";

    @Override
    public QueryWrapper<?> convert(String source) {
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        QueryWrapper<?> queryWrapper = new QueryWrapper<>();
        String zero = request.getParameter(query_wrapper);
        if(CommonUtil.isNotEmpty(zero)){
            JSONArray zeroArr = JSON.parseArray(zero);
            for (int i = 0; i < zeroArr.size(); i++) {
                JSONObject oneObj = (JSONObject) zeroArr.get(i);
                String operator = (String) oneObj.get(query_operator);
                String name = CommonUtil.dbHumpToDB((String) oneObj.get(query_name));
                Object value = oneObj.get(query_value);
                if(operator.equals(operator_in)){
                    JSONArray two = JSON.parseArray(value.toString());
                    List<String> list = JSONArray.toJavaObject(two , List.class);
                    queryWrapper.in(name,list);
                }else if(operator.equals(operator_like)){
                    queryWrapper.like(name,value);
                }else if (operator.equals(operator_eq)){
                    queryWrapper.eq(name,value);
                }else{
                    log.error("转化错误, 未知的操作符");
                    throw CustomizeRuntimeException.exception("未知的操作符");
                }
            }
        }
        return queryWrapper;
    }
}
